<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="role-span">供应商信息</span>
        <div class="box-card-btn" v-if="pageReady">
          <el-tag
            class="status-tag"
            :type="statusType[nsi.status]"
            v-if="dict.supplier_status && nsi.status"
          >
            {{ dict.label.supplier_status[nsi.status] }}
          </el-tag>
          <el-button type="success" @click="audit" :loading="posting" v-if="passedProfile">
            修改并重新提交审核
          </el-button>
          <!-- 在未审核状态 才能 -->
          <el-button
            type="primary"
            @click="audit"
            :loading="posting"
            v-if="!passedProfile && !initedProfile"
          >
            提交审核
          </el-button>
        </div>
      </div>
      <el-form
        :model="nsi"
        :disabled="initedProfile"
        ref="supplierForm"
        :rules="supplierRules"
        label-width="140px"
      >
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <!-- line -->
          <el-col :span="8">
            <el-form-item prop="name" label="供应商名称:">
              <el-input v-model="nsi.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商编码:">
              <div class="supplier-code" :class="{ active: nsi.code }">
                {{ nsi.code || '通过审核后,系统会自动分配' }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业性质:" prop="detail.property">
              <el-select v-model="nsi.detail.property" clearable filterable>
                <el-option
                  v-for="item in dict.enterprise_property"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="8">
            <el-form-item prop="uscc" label="统一社会信用代码:">
              <el-input v-model="nsi.uscc"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="contactPerson" label="联系人姓名:">
              <el-input v-model="nsi.contactPerson"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="contactPhone" label="联系人手机:">
              <el-input v-model="nsi.contactPhone"></el-input>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="8">
            <el-form-item prop="companyPhone" label="公司电话:">
              <el-input v-model="nsi.companyPhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.foundedAt" label="创立日期:">
              <el-date-picker
                v-model="nsi.detail.foundedAt"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="legalPerson" label="法人代表:">
              <el-input v-model="nsi.legalPerson"></el-input>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="16">
            <el-form-item prop="detail.address" label="公司地址:">
              <el-input v-model="nsi.detail.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.email" label="邮箱:">
              <el-input v-model="nsi.detail.email"></el-input>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="8">
            <el-form-item prop="detail.registeredFund" label="注册资金（万元）:">
              <el-input v-model="nsi.detail.registeredFund"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.fixedFund" label="固定资产（万元）:">
              <el-input v-model="nsi.detail.fixedFund"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.totalFund" label="总资产（万元）:">
              <el-input v-model="nsi.detail.totalFund"></el-input>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="16">
            <el-form-item prop="detail.majorProduct" label="主要产品:">
              <el-input
                v-model="nsi.detail.majorProduct"
                placeholder="多类别使用'/'分割, 例如: IT产品/运维"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.totalEmployees" label="员工总数:">
              <el-input v-model.number="nsi.detail.totalEmployees"></el-input>
            </el-form-item>
          </el-col>
          <!-- line -->
          <el-col :span="8">
            <el-form-item prop="detail.license" label="营业执照:">
              <el-upload
                class="upload-demo"
                accept="image/png, image/jpeg"
                :on-success="uploaded"
                :on-error="uploadError"
                :headers="{ Authorization: token }"
                :action="`${baseURL}/api/supplier/upload-license`"
                :limit="1"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5Mb</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="nsi.detail.license">
            <el-image
              :src="`${baseURL}/license/${nsi.detail.license}`"
              :preview-src-list="[`${baseURL}/license/${nsi.detail.license}`]"
              fit="contain"
              lazy
              class="profile-license"
            ></el-image>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="detail.expiredAt" label="有效期至:">
              <el-date-picker
                v-model="nsi.detail.expiredAt"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="availableStock" label="可供货品类:">
              <stock-tree v-model="nsi.availableStock"></stock-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">银行信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="detail.bank.line" label="开户行联行号:">
              <el-input v-model="nsi.detail.bank.line"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="detail.bank.branch" label="支行名称:">
              <el-input v-model="nsi.detail.bank.branch"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="detail.bank.accountNumber" label="银行账号:">
              <el-input v-model="nsi.detail.bank.accountNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="detail.bank.accountName" label="账号名称:">
              <el-input v-model="nsi.detail.bank.accountName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="box-card" shadow="never">
      <AuditRecordList :records="auditRecord" :hideOp="true"></AuditRecordList>
    </el-card>
  </div>
</template>

<script>
  import * as SupplierRequest from '@/api/supplier';
  import FormRuleConf from '@/FormRuleConf';
  import { getToken } from '@/utils/auth';
  import AuditRecordList from './auditRecordList';
  import StockTree from '@/components/StockTree';

  const DATA_TMP = {
    // 搜索项开始 ======
    name: '', // 供应商名称
    uscc: '', // 社会统一信用代码 Uniform social credit code
    contactPerson: '', // 联系人姓名
    contactPhone: '', // 联系人手机
    companyPhone: '', // 公司电话
    legalPerson: '', //法人姓名
    // 这个要根据stock来筛选公司 在邀请供应商的时候很有用
    availableStock: '', // 可供货品类，品类字典多选
    // 搜索项结束 ======

    detail: {
      property: '', //企业性质，字典枚举值
      foundedAt: '', // 创立日期
      address: '', // 公司地址
      email: '', // 邮箱

      registeredFund: '', // 注册资金(String) 单位：（万元）
      fixedFund: '', // 固定资产（String)  单位：（万元）
      totalFund: '', // 总资产（String)  单位：（万元）

      majorProduct: '', //主要产品，考虑 'aa/bb/cc'分割，便于查询？
      totalEmployees: '', // 员工总数

      license: '', //营业执照
      expiredAt: '', // 有效期
      bank: {
        line: '', // 开户行联行号
        branch: '', // 支行名称
        accountNumber: '', // 银行账号
        accountName: '', // 账号名称
      },
    },
  };

  export default {
    name: 'SupplierProfile',
    dicts: ['enterprise_property', 'supplier_status'],
    components: { AuditRecordList, StockTree },
    data() {
      return {
        ...FormRuleConf.Supplier,
        // newSupplierInfo
        nsi: { ...DATA_TMP },
        baseURL: process.env.VUE_APP_BASE_API,
        posting: false,
        token: getToken(),
        auditRecord: [],
        statusType: {
          PASS: 'success',
          INIT: 'warning',
          BLOCK: 'danger',
        },
        pageReady: false,
      };
    },
    computed: {
      initedProfile() {
        if (!this.nsi) return false;
        return this.nsi.status === 'INIT';
      },
      passedProfile() {
        if (!this.nsi) return false;
        return this.nsi.status === 'PASS';
      },
    },
    mounted() {
      this.getProfile();
      this.getAuditRecord();
    },
    methods: {
      getAuditRecord() {
        SupplierRequest.getMyAuditRecord().then((res) => {
          this.auditRecord = res.content;
        });
      },
      getProfile() {
        SupplierRequest.getProfile()
          .then((res) => {
            if (res) {
              const { detail } = res;
              this.nsi = { ...res };
              this.nsi.detail = detail ? JSON.parse(detail) : { ...DATA_TMP.detail };
            }
          })
          .catch((err) => {
            console.log(error);
            return true;
          })
          .finally(() => {
            this.pageReady = true;
          });
      },
      /**
       * 上传文件
       */
      uploaded(res, file, fileList) {
        const [result] = fileList;
        this.$set(this.nsi.detail, 'license', result.response.license);
      },
      /**
       * 上传文件失败
       */
      uploadError(err) {
        this.$message.error(err);
      },
      audit() {
        if (this.posting) return;

        this.$refs['supplierForm'].validate((valid) => {
          if (!valid) return;

          let request = this.nsi.code ? SupplierRequest.editSupplier : SupplierRequest.addSupplier;

          this.posting = true;

          const body = {
            ...this.nsi,
            detail: JSON.stringify(this.nsi.detail),
          };

          request(body)
            .then((res) => {
              this.getProfile();
              this.$message.success('提交审核成功,请等待审核结果!');
            })
            .catch((err) => {
              console.log(err);
            })
            .finally(() => {
              this.posting = false;
            });
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .supplier {
    &-profile {
    }

    &-code {
      color: #aaa;
      &.active {
        color: #333;
      }
    }
  }

  .status-tag {
    vertical-align: bottom;
    margin-right: 20px;
  }
</style>
